package com.example.deviceinfo.ui

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.deviceinfo.R
import com.example.deviceinfo.adapter.DeviceInfoAdapter
import com.example.deviceinfo.databinding.ActivityMainBinding
import com.example.deviceinfo.viewmodel.DeviceInfoViewModel
import com.example.deviceinfo.viewmodel.Resource
import com.scwang.smart.refresh.header.ClassicsHeader
import dagger.hilt.android.AndroidEntryPoint

/**
 * 提供一个获取接口设备信息，recycler view展示例子
 */
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val viewModel: DeviceInfoViewModel by viewModels()
    private val adapter = DeviceInfoAdapter()
    private var currentPage = 1
    private var isLoading = false
    private var isLastPage = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setupInsets()
        setupRecyclerView()
        setupRefreshLayout()
        observeViewModel()

        // 初始加载数据
        if (savedInstanceState == null) {
            viewModel.fetchDevices(1)
        }
    }

    private fun setupInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun setupRecyclerView() {
        binding.recyclerView.apply {
            adapter = this@MainActivity.adapter
            layoutManager = LinearLayoutManager(this@MainActivity)
            addItemDecoration(
                DividerItemDecoration(
                    this@MainActivity,
                    LinearLayoutManager.VERTICAL
                )
            )
            setHasFixedSize(true)

            // 监听滚动事件，实现上拉加载更多
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)

                    val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                    val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                    val totalItemCount = layoutManager.itemCount

                    // 当滚动到接近底部时，加载更多数据
                    if (!isLoading && !isLastPage &&
                        lastVisibleItemPosition >= totalItemCount - 5 && dy > 0
                    ) {
                        currentPage++
                        viewModel.fetchDevices(currentPage)
                    }
                }
            })
        }
    }

    private fun setupRefreshLayout() {
        binding.refreshLayout.apply {
            setRefreshHeader(ClassicsHeader(this@MainActivity))
            // 设置刷新监听 下拉刷新逻辑
            setOnRefreshListener { refreshLayout ->
                // 防止重复请求
                if (isLoading) {
                    refreshLayout.finishRefresh(false)
                    return@setOnRefreshListener
                }
                // 重置页码，触发刷新
                currentPage = 1
                viewModel.fetchDevices(currentPage, isRefresh = true)
                finishRefresh(2000)
            }

            // 设置加载更多监听, 上拉加载更多逻辑
            setOnLoadMoreListener {

                if (!isLoading && !isLastPage) {
                    currentPage++
                    viewModel.fetchDevices(currentPage)
                } else {
                    finishLoadMore()
                }
            }
            // 设置刷新主题颜色
            setPrimaryColorsId(R.color.red, android.R.color.white)
        }
    }

    private fun observeViewModel() {
        lifecycleScope.launchWhenStarted {
            viewModel.deviceList.observe(this@MainActivity) { resource ->
                when (resource) {
                    is Resource.Loading -> {
                        isLoading = true
                        if (resource.isInitialLoad) {
                            // 初次加载显示全局进度条
                            binding.progressBar.visibility = View.VISIBLE
                            binding.errorText.visibility = View.GONE
                            binding.recyclerView.visibility = View.GONE
                        } else if (resource.isRefresh) {
                            // 下拉刷新时不显示全局进度条
                            binding.progressBar.visibility = View.GONE
                        } else {
                            // 加载更多时显示加载更多状态
                            binding.refreshLayout.setNoMoreData(false)
                        }
                    }

                    is Resource.Success -> {
                        isLoading = false
                        binding.progressBar.visibility = View.GONE
                        binding.errorText.visibility = View.GONE
                        binding.recyclerView.visibility = View.VISIBLE

                        // 处理刷新完成
                        if (resource.isRefresh) {
                            binding.refreshLayout.finishRefresh(true)
                        } else {
                            binding.refreshLayout.finishLoadMore(true)
                        }

                        // 更新数据
                        if (resource.isRefresh || currentPage == 1) {
                            // 刷新或第一页数据，替换整个列表
                            adapter.submitList(resource.data)
                        } else {
                            // 加载更多数据，追加到现有列表
                            val currentList = adapter.currentList.toMutableList()
                            currentList.addAll(resource.data ?: emptyList())
                            adapter.submitList(currentList)
                        }

                        // 检查是否是最后一页
                        isLastPage = resource.data.isNullOrEmpty()
                        binding.refreshLayout.setNoMoreData(isLastPage)

                        // 处理空数据状态
                        if (adapter.itemCount == 0) {
                            showEmptyState()
                        }
                    }

                    is Resource.Error -> {
                        isLoading = false
                        binding.progressBar.visibility = View.GONE

                        // 处理刷新/加载更多失败
                        if (resource.isRefresh) {
                            binding.refreshLayout.finishRefresh(false)
                        } else {
                            binding.refreshLayout.finishLoadMore(false)
                        }

                        // 如果是初次加载失败，显示错误信息
                        if (adapter.itemCount == 0) {
                            binding.errorText.visibility = View.VISIBLE
                            binding.recyclerView.visibility = View.GONE
                            Log.d("TAG", resource.message.toString())
                            binding.errorText.text = resource.message ?: "加载失败，请重试"
                        } else {
                            // 否则显示Toast提示
                            Toast.makeText(this@MainActivity, resource.message, Toast.LENGTH_SHORT)
                                .show()
                        }
                    }
                }
            }
        }
    }

    private fun showEmptyState() {
        binding.errorText.visibility = View.VISIBLE
        binding.errorText.text = "暂无设备信息"
        binding.recyclerView.visibility = View.GONE
    }
}